<template>
  <div class="component component-service-test text-left">
    <div class="container-center">
      <div class="over-hidden">
        <router-link
          class="btn btn-default pull-right icon icon-arrowsleftline mt-lg"
          :to="getMicroRoute('/tools')"
        >
          返回列表</router-link>
        <h2 class="text-left">服务测试</h2>
      </div>
      <div class="row">
        <div class="col-xs-12 row-cell">
          <div class="clear-after pt-sm mb-sm">
            <div class="pull-left">
              <button class="btn btn-theme" type="button" v-if="this.envList.length > 0" @click="start">开始测试</button>
            </div>
            <div class="pull-right">
              <label style="font-weight:700">存储方式：</label>
              <span class="drop-hover btn-group-drop mr-md" :class="'dropdown'">
                <button class="btn btn-default" type="button">
                  <span class="drop-select">{{ currentStore.text }}</span>
                  <span class="caret"></span>
                </button>
                <ul class="dropmenu dropmenu-right">
                  <li class="menu-item" v-for="item in stores" :key="item.id">
                    <a class="item-link" href="javascript:void(0)" @click="handleChangeStore(item)">
                      {{ item.text }}
                    </a>
                  </li>
                </ul>
              </span>
              <span v-if="String(currentStore.id) === '1'">
                <span v-if="serviceInters && serviceInters.length" class="drop-hover btn-group-drop mr-md" :class="'dropdown'">
                  <button class="btn btn-default" type="button">
                    <span class="drop-select">服务列表</span>
                    <span class="caret"></span>
                  </button>
                  <ul class="dropmenu dropmenu-right">
                    <li class="menu-item" v-for="item in serviceInters" :key="item.id">
                      <a class="item-link item-service" href="javascript:void(0)" @click="handleChangeInter(item)">
                        <span :title="item.url">{{ item.interface }}</span>
                        <span @click.stop="handleDeleteInter(item)" class="icon icon-icon_delete"></span>
                      </a>
                    </li>
                  </ul>
                </span>
                <a @click="handleSaveInter" class="btn btn-default mr-md">存储</a>
                <a @click="handleInsertInter" class="btn btn-default mr-md">另存</a>
                <a @click="handleExportInter" class="btn btn-default mr-md">导出</a>
              </span>
              <span v-else>
                <span v-if="serviceCache && serviceCache.length" class="drop-hover btn-group-drop" :class="'dropdown'">
                  <button class="btn btn-default" type="button">
                    <span class="drop-select">服务列表</span>
                    <span class="caret"></span>
                  </button>
                  <ul class="dropmenu dropmenu-right">
                    <li class="menu-item" v-for="item in serviceCache" :key="item.id + item.list[0].interface">
                      <a class="item-link item-service" href="javascript:void(0)" @click="handleChangeService(item)">
                        <span :title="item.list[0].url">{{ item.list[0].interface }}</span>
                        <span @click.stop="handleDeleteService(item)" class="icon icon-icon_delete"></span>
                      </a>
                    </li>
                  </ul>
                </span>
                <a @click="saveService" class="btn btn-default mr-md">存储</a>
                <a @click="handleSaveNew" class="btn btn-default mr-md">另存</a>
                <a class="btn btn-default btn-file mr-md">
                  导入
                  <input @change="handleImport" class="form-file" accept="application/json" type="file" />
                </a>
                <a @click="handleExportShow" class="btn btn-default mr-md">导出</a>
              </span>
              <Pipe type="down" />
            </div>
          </div>
          <div class="container-result">
            <div class="list-result">
              <form class="well well-xs list-item" v-for="(serve, i) in envList" :key="i + serve.serve">
                <div class="mt-md">
                  <span class="text-primary">测试接口数：<b>{{serve.list.length || 0}}</b>&emsp;</span>
                  <span class="text-success">接口成功数：<b>{{serve.successCount || 0}}</b>&emsp;</span>
                  <span class="text-info">成功率：<b>{{(100 * (serve.successCount || 0) / (serve.list.length || 1)).toFixed(2)}}%</b>&emsp;</span>
                </div>
                <div class="item-row form-table mt-md" v-for="(item, i) in serve.list" :key="i">
                  <div class="form-group">
                    <label class="form-label">接口名称:</label>
                    <div class="form-wall">
                      <input class="form-input" type="text" v-model="item.interface" />
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">状态:</label>
                    <div class="form-wall">
                      <span class="form-text">{{item.process}}</span>
                      <ProgressPointers v-if="item.process === processList.start" />
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">请求地址:</label>
                    <div class="form-wall">
                      <input
                        class="form-input" type="text"
                        placeholder="示例：http://127.0.0.1:8080"
                        v-model="item.url"
                      />
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">请求类型:</label>
                    <div class="form-wall">
                      <select class="form-select" v-model="item.method">
                        <option value="post">post</option>
                        <option value="get">get</option>
                        <option value="put">put</option>
                        <option value="delete">delete</option>
                        <option value="jsonp">jsonp</option>
                      </select>
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">请求参数:</label>
                    <div class="form-wall">
                      <textarea class="form-textarea" rows="8" v-model="item.params"></textarea>
                      <button
                        class="btn btn-default btn-sm mt-sm ml-xs"
                        type="button"
                        @click="item.params = format(item.params)"
                      >格式化</button>
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">请求头<i class="icon icon-icon_yiwenkongxin" title="环境存在权限验证时，可通过设置头数据通过验证"></i>:</label>
                    <div class="form-wall">
                      <table class="table table-striped table-bordered table-hover">
                        <thead>
                          <tr>
                            <th class="wide-lg">头名</th>
                            <th>头值</th>
                            <th class="wide-sm">操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="(head, h) in item.headerList" :key="h">
                            <td>
                              <div>
                                <input
                                  class="form-input" type="text"
                                  v-model="head.name"
                                />
                              </div>
                            </td>
                            <td>
                              <div>
                                <textarea
                                  class="form-textarea form-textarea-neat"
                                  v-model="head.value"
                                ></textarea>
                              </div>
                            </td>
                            <td class="vlign-mid text-left">
                              <div class="wide-sm">
                                <a
                                  class="text-link icon icon-icon_add" title="添加"
                                  @click="handleAddHeader(item)"
                                ></a>
                                <a
                                  class="text-link icon icon-icon_delete" title="删除"
                                  @click="handleDelHeader(item, head)"
                                ></a>
                              </div>
                            </td>
                          </tr>
                          <tr v-if="!item.headerList || item.headerList.length < 1">
                            <td class="text-center" colspan="3">
                              <a
                                class="text-link icon icon-icon_add" title="添加"
                                @click="handleAddHeader(item)"
                              ></a>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                      <button
                        class="btn btn-default btn-sm mt-sm mr-md"
                        type="button"
                        title="点击同步至其他接口头数据"
                        @click="syncHeaders(item)">
                        同步数据
                      </button>
                      <button
                        class="btn btn-default btn-sm mt-sm mr-md"
                        type="button"
                        @click="resetHeaders(item)">
                        重置头数据
                      </button>
                      <button
                        class="btn btn-default btn-sm mt-sm"
                        type="button"
                        @click="toggleResolveHeader">
                        解析头数据
                      </button>
                      <div v-if="isShowResolveHeader" style="padding-top: 8px;">
                        <textarea class="form-textarea" rows="8" v-model="headers"></textarea>
                        <div class="text-left">
                          <button
                            class="btn btn-default btn-sm mt-sm"
                            type="button"
                            @click="resolveHeaders(item)"
                          >解析</button>
                        </div>
                      </div>
                      <div class="mt-sm text-gray">常用请求头：cookie、token、authorization、referer、host、origin、content-type、accept-language、accept-encoding</div>
                      <div class="mt-sm text-gray" v-if="!i">设置cookie -> 在已登录的页面控制台输入：<span class="text-danger">document.cookie</span>；在头数据设置{cookie: '取得的cookie数据字符串'}</div>
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">响应头:</label>
                    <div class="form-wall">
                      <input
                        class="form-input" type="text"
                        placeholder='必须为JSON格式,示例：{"Access-Control-Expose-Headers": "token"}'
                        v-model="item.proxyresheaders"
                      />
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="form-label">数据类型:</label>
                    <div class="form-wall">
                      <select class="form-select" v-model="item.dataCate">
                        <option value="object">Object</option>
                        <option value="formdata">FormData</option>
                      </select>
                    </div>
                  </div>
                  <div class="form-group" v-show="isShow(item)">
                    <label class="form-label">状态码:</label>
                    <div class="form-wall"><div class="form-text">{{item.status}}</div></div>
                  </div>
                  <div class="form-group" v-show="isShow(item)">
                    <label class="form-label">响应时长<i class="icon icon-icon_yiwenkongxin" title="小于1000ms为优质接口"></i>:</label>
                    <div class="form-wall">
                      <div class="form-text"
                        :class="item.time < 1000 ? 'text-success' : 'text-danger'">{{item.time}}ms</div>
                      </div>
                  </div>
                  <div class="form-group" v-show="isShow(item)">
                    <label class="form-label">是否成功:</label>
                    <div class="form-wall">
                      <div class="form-text" :class="item.isSuccess ? 'text-success' : 'text-danger'">
                        {{item.isSuccess ? '是' : '否'}}
                      </div>
                    </div>
                  </div>
                  <div class="form-group" v-show="isShow(item)">
                    <label class="form-label">是否匹配:</label>
                    <div class="form-wall">
                      <div class="form-text" :class="item.isMatch ? 'text-success' : 'text-danger'">
                        {{item.isMatch ? '是' : '否'}}
                      </div>
                    </div>
                  </div>
                  <div class="form-group" v-show="isShow(item)">
                    <label class="form-label">响应数据:</label>
                    <div class="form-wall">
                      <textarea class="form-textarea" rows="8" v-model="item.result"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <div class="clear pt-sm mb-sm">
            <div class="pull-left">
              <button class="btn btn-theme" type="button" v-if="this.envList.length > 0" @click="start">开始测试</button>
            </div>
            <div class="pull-right">
              <Pipe name="proxy" :operation="{inputData: outputData}" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <DialogerComp ref="downloadView" title="下载文件" @sure="handleExport" width="500px">
      <template v-slot:body>
        <div class="form-group">
          <label class="form-label">名称:</label>
          <input
            type="text" class="form-input"
            v-model="downloadName"
          />
        </div>
      </template>
    </DialogerComp>
  </div>
</template>

<script>
/* 服务测试 */
import objecter from '../../../components/objecter/objecter'
import dtoolsSer, { api } from '../../../service/action/dtools.action'
import requester from '../../../service/components/requester'
import messager from '../../../components/messager/messager.js'
import Pipe from '../index/pipe.vue'
import ProgressPointers from '@/components/vue/components/progress/pointers.vue'
import {
  openDB,
  addData,
  cursorGetData,
  getDataByKey,
  updateDB,
  closeDB
} from '../../../components/indexeddb/indexeddb.js'
import { filer, parser } from '@daelui/dogjs/dist/components'
import DialogerComp from '../../../components/dialoger/dialoger.vue'

export default {
  components: {
    Pipe, ProgressPointers, DialogerComp
  },

  data () {
    return {
      inputData: '',
      outputData: '',
      isPipe: false,

      // 接口对象
      inter: {},
      inters: [{
        'id': new Date().getTime(),
        'interface': '服务测试',
        'url': '',
        'method': 'post',
        'dataCate': 'object',
        'proxyresheaders': '',
        'status': 1,
        'sort': 0,
        'desc': '',
        'explain': '',
        'isBuildService': 1,
        'developer': '',
        'protocol': '',
        'server': '',
        'request': {
          'params': [
            {
              'level': 0,
              'type': 'string',
              'required': 1,
              'id': 0.7005941603469441,
              'pid': 0,
              'rule': '',
              'value': '',
              'desc': '',
              'valid': '1'
            }
          ],
          'type': 'application/json'
        },
        'response': {
          'params': [
            {
              'level': 0,
              'name': 'object',
              'type': 'object',
              'required': 1,
              'rule': '',
              'desc': '',
              'id': 0.9251733089996854,
              'pid': 0,
              'value': '',
              'ruleValue': ''
            }
          ],
          'type': 'application/json'
        }
      }],
      // 测试列表
      envList: [],
      // 选择的服务列表
      checkedServe: [
        {
          'serve': 'dev',
          'name': '开发环境',
          'static': true,
          'rules': [],
          'id': new Date().getTime()
        }
      ],
      // 是否显示状态
      isShowStatus: false,
      // 选择的状态
      checkedStatus: [],
      processList: {
        unReady: '未开始测试',
        create: '生成请求参数中...',
        ready: '准备测试',
        start: '等待服务响应',
        end: '响应完成'
      },
      // 缓存的服务
      serviceCache: [],
      // 是否显示头解析器
      isShowResolveHeader: false,
      headers: '',
      downloadName: '',
      serviceInters: [],
      stores: [
        { id: '1', text: '服务端存储' },
        { id: '2', text: '本地存储' }
      ],
      currentStore: { id: '1', text: '服务端存储' }
    }
  },

  methods: {
    /**
     * @function 解析接口
     * @param {Object} inters // 接口对象
     * @param {Object} serve // 服务对象
     * @return {Object}
    */
    resolveInter (inters, serve) {
      let newServe = objecter.extend(true, {}, serve)
      // 测试列表
      newServe.list = []
      inters.forEach(item => {
        let url = String(item.url)
        // 地址解析
        newServe.rules.forEach(rule => {
          url = url.replace(rule.rule, rule.url)
        })
        // 转义字符解析
        url = url.replace(/.*(https?:)/i, '$1')
        // 初始化状态
        newServe.list.push(objecter.extend(true, {}, item, {
          url: url,
          headers: '',
          proxyresheaders: '',
          // 默认请求头
          headerList: [
            {name: 'cookie', value: ''},
            {name: 'token', value: ''},
            {name: 'authorization', value: ''},
            {name: 'referer', value: ''}
          ],
          params: this.inputData,
          dataCate: 'object',
          process: this.processList.unReady,
          isSuccess: false,
          status: 0,
          time: 0,
          isMatch: false,
          result: ''
        }))
      })
      return newServe
    },

    /**
     * @function 生成测试
    */
    build () {
      if (this.checkedServe.length < 1) {
        messager.warning('请选择测试环境')
        return false
      }
      // 解析接口为测试列表
      this.envList = this.checkedServe.map((item) => {
        item.id = item.id || new Date().getTime()
        let inters = this.inters
        // 匹配选中状态的接口
        if (this.isShowStatus) {
          inters = this.inters.filter(item => {
            let isCheck = false
            this.checkedStatus.forEach(node => {
              if (String(node) === String(item.status)) {
                isCheck = true
              }
            })
            return isCheck
          })
        }
        return this.resolveInter(inters, item)
      })
      // 获取存储的环境列表
      let storeEnvList = this.getStore()
      if (Array.isArray(storeEnvList) && storeEnvList.length) {
        this.envList = storeEnvList
      }
      // 遍历环境列表
      this.envList.forEach(item => {
        // 遍历环境下的接口列表
        item.list.forEach(inter => {
          inter.process = this.processList.ready
        })
      })
    },

    /**
     * @function 开始测试
    */
    start () {
      // 遍历环境列表
      this.envList.forEach(item => {
        // 成功数置0
        item.successCount = 0
        // 遍历环境下的接口列表
        item.list.forEach(inter => {
          let dateStart = new Date()
          // 头处理
          let headers = this.getHeaders(inter)
          // 参数处理
          let params = inter.params
          try {
            params = (new Function('return ' + inter.params))()
          } catch (e) {
            params = inter.params
          }
          // 数据类型
          if (inter.dataCate === 'formdata' && objecter.isPlainObject(params)) {
            let fd = new FormData()
            for (let key in params) {
              fd.append(key, params[key])
            }
            params = fd
          }
          // 访问测试环境
          inter.process = this.processList.start
          let defer = requester.request({
            serve: item.serve,
            method: inter.method,
            url: api.proxy.url,
            headers: {
              proxyurl: inter.url,
              proxyheaders: JSON.stringify(headers || {}),
              proxyresheaders: inter.proxyresheaders
            },
            data: params,
            // 请求完成
            complete: (result) => {
              inter.process = this.processList.end
              // 解析
              this.resolveResult(inter, result, dateStart)
              if (inter.isSuccess) {
                item.successCount += 1
              }
            },
            withCredentials: true
          })

          return defer
        })
      })
      // 存储的环境列表
      this.setStore()
    },

    /**
     * @function 存储的环境列表
    */
    setStore () {
      let storeEnvList = JSON.stringify(this.envList)
      sessionStorage.setItem('storeEnvList', storeEnvList)
      localStorage.setItem('storeEnvList', storeEnvList)
    },

    /**
     * @function 获取存储的环境列表
    */
    getStore () {
      let sessionEnvList = sessionStorage.getItem('storeEnvList')
      let storeEnvList = localStorage.getItem('storeEnvList')
      if (storeEnvList) {
        try {
          storeEnvList = JSON.parse(storeEnvList)
        } catch (e) {
          storeEnvList = []
        }
      }
      if (sessionEnvList) {
        try {
          sessionEnvList = JSON.parse(sessionEnvList)
        } catch (e) {
          sessionEnvList = []
        }
      }
      let result = Array.isArray(sessionEnvList)
        ? sessionEnvList
        : Array.isArray(storeEnvList)
        ? storeEnvList
        : []

      return result
    },

    /**
     * @function 解析结果
    */
    resolveResult (inter, result, dateStart) {
      // 转换数据
      let data = requester.parse(result.responseText, 'object') || result.responseText
      let status = result.status
      // 响应数据
      inter.result = this.pretty(data)
      // 耗时
      inter.time = (new Date()).getTime() - dateStart.getTime()
      // 状态码
      inter.status = status
      // 成功
      inter.isSuccess = status >= 200 && status <= 304
      // 是否匹配
      inter.isMatch = this.matchResult(data, inter.response.params)
      // 输出设置
      this.outputData = result.responseText
    },

    /**
    * @function 匹配结果与参数
    * @param {Object} data
    * @param {Object} params
    * @return {Boolean}
    */
    matchResult (data, params) {
      let isMatch = true
      params = Array.isArray(params) ? params : []
      params.forEach(item => {
        // 不匹配
        if (!(item.required && item.type === typeof data)) {
          isMatch = false
        }
      })

      return isMatch
    },

    /**
    * @function 美化模拟数据
    * @param {Object} data
    * @return {Object}
    */
    pretty (data) {
      if (typeof data === 'object') {
        data = JSON.stringify(data, null, 2)
      }
      return data
    },

    /**
     * @function 添加头数据
    */
    handleAddHeader (inter) {
      inter.headerList = Array.isArray(inter.headerList) ? inter.headerList : []
      inter.headerList.push({
        name: '',
        value: ''
      })
      this.$set(inter, 'headerList', inter.headerList)
    },

    /**
     * @function 删除头数据
    */
    handleDelHeader (inter, head) {
      inter.headerList = inter.headerList.filter(item => {
        return head !== item
      })
      this.$set(inter, 'headerList', inter.headerList)
    },

    /**
    * @function 是否显示结果
    * @param {Object} inter
    * @return {Boolean}
    */
    isShow (inter) {
      return inter.process === this.processList.end
    },

    /**
    * @function 获取头数据
    * @param {Object} inter
    * @return {Object}
    */
    getHeaders (inter) {
      let headers = {}
      let headerList = Array.isArray(inter.headerList) ? inter.headerList : []
      // 遍历头数据列表并取出有效数据
      headerList.forEach(item => {
        let name = String(item.name).trim().replace(/^[\\"\\']+|[\\"\\']+$/g, '')
        let value = String(item.value).trim().replace(/^[\\"\\']+|[\\"\\']+$/g, '')
        if (name && value) {
          headers[name] = value
        }
      })

      return headers
    },

    /**
     * @function 同步头数据
    * @param {Object} item // 测试实例
    */
    syncHeaders (item) {
      this.envList.forEach(serve => {
        serve.list.forEach(node => {
          if (item !== node) {
            node.headerList = objecter.clone(item.headerList)
          }
        })
      })
    },

    /**
     * @function 格式化处理
    */
    format (data, toStr) {
      let param = data
      try {
        param = (new Function('return ' + data))()
      } catch (e) {
        param = data
        messager.warning('数据非JSON格式，格式化失败')
      }
      // 对象形式格式化
      if (typeof param === 'object' && toStr !== false) {
        param = JSON.stringify(param, null, 2)
      }

      return param
    },

    /**
     * @function 初始化服务
    */
    loadCacheList () {
      openDB('dog-df3s-dtools', 'service-cache').then(db => {
        cursorGetData(db, 'service-cache').then(list => {
          this.serviceCache = list
        })
        closeDB(db) // 关闭数据库
      })
    },

    /**
     * @function 保存服务
    */
    saveService () {
      let inter = this.envList[0]
      openDB('dog-df3s-dtools', 'service-cache').then(db => {
        let data = getDataByKey(db, 'service-cache', inter.id)
        if (data) {
          updateDB(db, 'service-cache', inter)
        } else {
          addData(db, 'service-cache', inter)
        }
        closeDB(db) // 关闭数据库
        this.loadCacheList()
      })
    },

    /**
     * @function 另存服务
    */
    handleSaveNew () {
      this.saveNewService(this.envList[0])
    },

    /**
     * @function 另存服务
    */
    saveNewService (inter) {
      inter = inter || this.envList[0]
      openDB('dog-df3s-dtools', 'service-cache').then(db => {
        inter.id = new Date().getTime() + Math.floor(100000 * Math.random())
        addData(db, 'service-cache', inter) // 新增数据
        closeDB(db) // 关闭数据库
        this.loadCacheList()
      })
    },

    /**
     * @function 删除服务
    */
    handleDeleteService (node) {
      this.serviceCache =  this.serviceCache.filter(item => {
        return item.id !== node.id
      })
      openDB('dog-df3s-dtools', 'service-cache').then(db => {
        deleteDB(node.id)
        closeDB(db) // 关闭数据库
      })
      this.saveNewService(this.envList[0])
    },

    /**
     * @function 切换服务处理
    */
    handleChangeService (item) {
      this.envList = [item]
    },

    /**
     * @function 导入
    */
    handleImport (e) {
      let files = e.target.files
      filer.readFileText(files[0]).then(text => {
        try {
          let data = JSON.parse(text)
          data = Array.isArray(data) ? data : []
          data = data.filter(item => {
            let b = true
            this.serviceCache.forEach(sc => {
              if (String(sc.id) === String(item.id)) {
                b = false
              }
            })
            if (!item.id) {
              b = false
            }
            return b
          })
          data.forEach(item => {
            this.saveNewService(item)
          })
        } catch (e) {}
      })
    },

    /**
     * @function 导出确认
    */
    handleExportShow (isServiceExport) {
      this.downloadName = 'dtools-service-' + new Date().getTime() + '.json'
      this.isServiceExport = isServiceExport
      this.$refs.downloadView.show()
    },

    /**
     * @function 导出
    */
    handleExport () {
      let data = this.serviceCache || []
      if (this.isServiceExport) {
        data = this.serviceInters || []
      }
      data = JSON.stringify(cache, null, '\t')
      this.downloadName = this.downloadName || 'dtools-service-' + new Date().getTime() + '.json'
      filer.downloadFile(this.downloadName, data)
      this.$refs.downloadView.hide()
    },

    toggleResolveHeader () {
      this.isShowResolveHeader = !this.isShowResolveHeader
    },

    /**
     * @function 解析头
    */
    resolveHeaders (serve) {
      let headers = this.headers
      let parsed = parser.parse(headers)
      let items = []
      // 对象形式
      if (typeof parsed !== 'object') {
        let list = headers.split('\n')
        list.forEach(item => {
          let arr = item.split(/:\s/)
          let key = arr[0].trim()
          let value = arr.splice(1).join(': ')
          items.push({name: key, value: value})
        })
      }
      // 只取request头
      // 转换为数组
      if (objecter.isPlainObject(parsed)) {
        for (let key in parsed) {
          items.push({name: key, value: parsed[key]})
        }
      }
      // 过滤重复项
      items = items.filter(item => {
        let b = true
        serve.headerList.forEach(node => {
          if (String(item.name).toLowerCase() === String(node.name).toLowerCase()) {
            node.value = item.value
            b = false
          }
        })
        if (!item.name || !item.value) {
          b = false
        }
        return b
      })
      // 合并
      serve.headerList = serve.headerList.concat(items)
    },

    // 重置头
    resetHeaders (inter) {
      inter.headerList = [
        {name: 'cookie', value: ''},
        {name: 'token', value: ''},
        {name: 'authorization', value: ''},
        {name: 'referer', value: ''}
      ]
    },

    // 加载接口列表
    loadInterList () {
      dtoolsSer.queryInterList().then(res => {
        let list = res.data
        list = Array.isArray(list) ? list : []
        this.serviceInters = list
      })
    },

    // 切换服务接口
    handleChangeInter (item) {
      this.envList[0].list = [item]
    },

    // 加载接口列表
    handleInsertInter () {
      let env = this.envList[0]
      let inter = env.list[0]
      dtoolsSer.insertInter(inter).then(res => {
        inter.id = res?.data
      })
    },

    // 更新接口
    handleSaveInter () {
      let env = this.envList[0]
      let inter = env.list[0]
      if (inter.id) {
        dtoolsSer.updateInter(inter)
      } else {
        dtoolsSer.insertInter(inter)
      }
    },

    // 删除接口
    handleDeleteInter (node) {
      this.serviceInters = this.serviceInters.filter(item => {
        return item.id !== node.id
      })
      dtoolsSer.deleteInter({ id: node.id })
    },

    // 导出接口
    handleExportInter () {
      this.handleExportShow()
    },

    handleChangeStore (node) {
      this.currentStore = node
    }
  },

  mounted () {
    // 管道数据
    if (this.$store.state.inputData) {
      this.inputData = this.$store.state.inputData
      this.$store.state.inputData = ''
    }
    // 初始化
    this.build()
    // 初始化缓存服务
    this.loadCacheList()
    // 初始化服务存储的服务
    this.loadInterList()
  }
}
</script>

<style lang="less">
.container-result{
  padding:0 5px;
  .form-table{
    table-layout: fixed;
    border-top: 1px solid #dedede;
  }
  .form-label{
    width: 100px;
    white-space: nowrap;
  }
  .form-text{
    word-wrap: break-word;
    word-break: normal;
  }
  .text-name{
    color: #1abd9e;
  }
}
.btn-file {
  overflow: hidden;
  position: relative;
}
.form-file {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
}
.dropmenu .item-link {
  &.item-service {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
